package com.example.studyPlatform.service;

import com.example.studyPlatform.bean.Post;
import com.example.studyPlatform.mapper.PostMapper;
import com.example.studyPlatform.service.protocol.PostService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class PostServiceImpl implements PostService {

    PostMapper postMapper;

    public PostServiceImpl(PostMapper postMapper) {
        this.postMapper = postMapper;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Post publish(int type, int author, boolean disallowComment, String title, String summary, String thumbnail, String content) {
        Post post = new Post();
        post.setAuthor(author);
        post.setDisallowComment(disallowComment);
        post.setTitle(title);
        post.setSummary(summary);
        post.setThumbnail(thumbnail);
        post.setContent(content);
        double r = Math.random();
        if (r < 0.4) {
            post.setVisits(0L);
        } else if (r < 0.666) {
            post.setVisits(1L);
        } else
            post.setVisits(2L);
        post.setCommentsNumber(0);
        postMapper.publish(post);
        return post;
    }
}
